package everyday.m20230309;

import java.util.*;

public class Q20230311 {

    public static void main(String[] args) {
        Q20230311 q20230311 = new Q20230311();
        System.out.println(Arrays.toString(q20230311.findLongestSubarray(new String[]{
                "A","1","B","C","D","2","3","4","E","5","F","G","6","7","H","I","J","K","L","M"
        })));
        System.out.println(Arrays.toString(q20230311.findLongestSubarray(new String[]{
                "A","A"
        })));
    }

    public String[] findLongestSubarray(String[] array) {
        // 将前缀和记录下来
        Map<Integer, Integer> indices = new HashMap<>();
        indices.put(0, -1);
        int sum = 0;
        int maxIndex = -1,maxSize = 0;
        for (int i = 0; i < array.length; i++) {
            if (Character.isLetter(array[i].charAt(0))) {
                sum ++;
            } else {
                sum --;
            }
            if (indices.containsKey(sum)) {
                // 获取第一次出现的时候
                Integer firstIndex = indices.get(sum);
                // 从first开始
                if (i - firstIndex > maxSize) {
                    maxIndex = firstIndex + 1;
                    maxSize = i - firstIndex;
                }
            } else {
                // 第一次出现sum
                indices.put(sum, i);
            }
        }
        if (maxSize == 0) {
            return new String[0];
        }
        return Arrays.copyOfRange(array,maxIndex, maxIndex + maxSize);
    }
}
